package com.chinamobile.iot.mqtt.spi.impl.security;

import com.chinamobile.iot.mqtt.spi.security.IAuthenticator;
import com.chinamobile.iot.mqtt.spi.security.MqttClientInfo;
import com.chinamobile.iot.utils.UuidUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by andrea on 8/23/14.
 */

@Component
@ConditionalOnExpression("${mqtt.anonymous}")
public class AcceptAllAuthenticator implements IAuthenticator {

    private ConcurrentHashMap<String, MyMqttClientInfo> clients = new ConcurrentHashMap<>();

    @Override
    public MqttClientInfo loginCheck(String clientId, String username, String password) {
        MyMqttClientInfo clientInfo = clients.get(clientId);
        if (clientInfo != null){
            return clientInfo;
        }
        else{
            clientInfo = new MyMqttClientInfo();
            clients.put(clientId, clientInfo);
            return clientInfo;
        }
    }

    @Override
    public String getRspTopic(MqttClientInfo clientInfo, String clientId) {
        return "rsp/welcome";
    }

    @Override
    public void onClientDisconnected(String clientId, String mqttId) {

    }

    public static class MyMqttClientInfo implements MqttClientInfo {
        private final String id = UuidUtils.getUuid();
        @Override
        public String getId() {
            return id;
        }
    }

}
